#!/usr/bin/python
import json
import os
import random
import socket
import string

import sys

import time


class Admin:
    clientSock = "/tmp/client.sock"
    managerSock = "/tmp/shadowsocks-manager.sock"

    def __init__(self):
        if os.path.exists(self.clientSock):
            os.remove(self.clientSock)
        self.cli = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        self.cli.bind(self.clientSock)  # address of the client
        self.cli.connect(self.managerSock)  # address of Shadowsocks manager

    def ping(self):
        self.cli.send(b'ping')
        print(self.cli.recv(1506))  # You'll receive 'pong'

    def add(self, port="8001", password="111111"):
        self.cli.send(b'add: {"server_port":%s, "password":"%s"}' % (port, password))
        print(self.cli.recv(1506))  # You'll receive 'ok'

    def remove(self, port="8001"):
        self.cli.send(b'remove: {"server_port":%s}' % port)
        print(self.cli.recv(1506))  # You'll receive 'ok'

    def stat(self, port="8001"):
        self.cli.send(b'stat')
        print(self.cli.recv(1506))  # You'll receive 'ok'

    def close(self):
        self.cli.close()


if __name__ == '__main__':
    flag = ""
    if len(sys.argv) == 1 or len(sys.argv[1]) == 0:
        flag = "stat"
    else:
        flag = sys.argv[1]

    if flag == "stat":
        output = [{"endpoint": "DKPC", "tags": "server=shadowsocks", "timestamp": int(time.time()), "metric": "ssserver.password",
                   "value": "password", "counterType": "GAUGE", "step": 60}]

        print json.dumps(output)
    elif flag == "init":
        admin = Admin()
        admin.remove()
        admin.add()
        admin.close()


def randomPassword():
    return ''.join(random.sample(string.ascii_letters + string.digits, 18))
